package com.patrol.auth.jwt;


import com.patrol.auth.pojo.AdminUser;
import com.patrol.auth.service.AdminUserService;
import com.patrol.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author 房梦豪
 * @version 1.0
 * @description: TODO
 * @date 2021/9/28 15:55
 */
@Slf4j
@Service
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private AdminUserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof com.fmh.jwt.JWTToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        获取token中的username
//        String username = JWTUtil.getUsername(principalCollection.toString());
//
//        AdminUser user = userService.selectUserByUserName(username);
//
//        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
////        添加角色
////        simpleAuthorizationInfo.addRole(user.getAuthority());
////        将权限分割存入set集合
////        Set<String> permission = new HashSet<>(Arrays.asList(user.getPermission().split(",")));
////        添加权限集合
//        simpleAuthorizationInfo.addStringPermissions(null);

        return null;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
//        获取证书
        String token = (String)auth.getCredentials();
//        解密获得username，用于和数据库进行对比
        String username = JWTUtil.getUsername(token);

        if (username == null) {
            throw new AuthenticationException("token invalid");
        }

        AdminUser user = userService.selectUserByUserName(username);
        if (null == user) {
            throw new AuthenticationException("user didn't existed");
        }

        if (!JWTUtil.verify(token, username, user.getPassword())) {
            throw new AuthenticationException("username or password is error");
        }

        return new SimpleAuthenticationInfo(token, token, "my_realm");
    }
}
